package com.txh.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by Administrator on 2018/10/22.
 */
@Controller
@RequestMapping("/sso")
public class AuthController {

    @RequestMapping("/auth")
    public String auth(String userName, String password,String callBackUrl, Model model, HttpSession session,HttpServletRequest request){
        //生成token
        String token = UUID.randomUUID().toString().substring(0,16);
        if (userName == null&&password == null){
            return "login";
        }
        if ("admin".equals(userName) && "admin".equals(password)){
            //记录登录状态
            session.setAttribute("flag",true);
            session.setAttribute("token",token);
            return "index";
        }else{
            model.addAttribute("error","用户名或密码错误");
            return "login";
        }

    }

    @RequestMapping("/verifi")
    @ResponseBody
    public JSONObject vifer(HttpServletRequest request,HttpSession session){
        //获取token
        String authToken = request.getParameter("token");
        String token = (String) session.getAttribute("token");
        JSONObject jsonObject = new JSONObject();
        if (token.equals(authToken) && token !=null){
            jsonObject.put("code","200");
            jsonObject.put("info","token认证成功");
        }else{
            jsonObject.put("code","400");
            jsonObject.put("info","token认证失败");
        }
        return jsonObject;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public JSONObject logOut(HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        HttpSession session = request.getSession();
        if (session == null){

        }else {
            session.invalidate();
            jsonObject.put("info","注销成功");
            jsonObject.put("code", HttpStatus.OK);
        }
        return jsonObject;
    }
}
